package com.cjx.admin.controller;


import cn.hutool.core.util.ObjectUtil;
import com.cjx.admin.api.AdminUserService;
import com.cjx.admin.dto.AdminLoginDTO;
import com.cjx.admin.dto.AdminUserDTO;
import com.cjx.admin.dto.AdminUserInfoDTO;
import com.cjx.common.api.CommonResult;
import com.cjx.common.api.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 *
 * 用户管理控制层
 *
 * @author : cjunxian
 * @since 2021-03-11
 * @version 1.0
 */
@Api(tags = "用户管理控制层",value = "AdminUserController")
@RestController
@RequestMapping("adminUser")
@Validated
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;

    /**
    *@Description 登陆
    *@Verson v1.0.0
    *@Author cjunxian
    *@Date
    */
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username", value = "用户名", dataType = "String",required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String",required = true)
    })
    @ApiOperation("登陆并返回token")
    @PostMapping("/login")
    public CommonResult login(@RequestBody AdminLoginDTO login){
        return adminUserService.login(login.getUsername(), login.getPassword());
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public CommonResult register(@RequestBody AdminUserDTO user){
        AdminUserDTO register = adminUserService.addUser(user);
        if(ObjectUtil.isNotNull(register)){
            return CommonResult.success(register);
        }else {
            return CommonResult.failed("注册失败！");
        }
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @ApiOperation("更新用户")
    @PostMapping("/updateUser")
    public CommonResult updateUser(@RequestBody AdminUserDTO user){
        if(ObjectUtil.isNull(user.getId())){
            return CommonResult.failed("用户更新失败！id不能为空！");
        }else {
            return CommonResult.success(adminUserService.updateUser(user));
        }
    }

    /**
     * 根据id获取用户信息
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("getUserByUsername/{username}")
    public CommonResult<AdminUserInfoDTO> getUserByUsername(@PathVariable("username")String username){
        AdminUserInfoDTO user = adminUserService.getUserByUsername(username);
        if(ObjectUtil.isNull(user)){
            return CommonResult.failed(ResultCode.USER_NOT_EXIST);
        }
        return CommonResult.success(user);
    }


}
